document.addEventListener('DOMContentLoaded', async function() {
  const selectFileBtn = document.getElementById('selectFile');
  const startImportBtn = document.getElementById('startImport');
  const fileInput = document.getElementById('excelFile');
  const statusDiv = document.getElementById('status');
  let selectedFile = null;

  // 检查当前页面
  const [tab] = await chrome.tabs.query({active: true, currentWindow: true});
  if (!tab?.url?.includes('zf.scetop.com')) {
    statusDiv.textContent = '请在教务系统页面使用';
    statusDiv.classList.add('error');
    selectFileBtn.disabled = true;
    startImportBtn.disabled = true;
    return;
  }

  // 注入脚本
  await chrome.scripting.executeScript({
    target: { tabId: tab.id },
    files: ['xlsx.full.min.js', 'content.js']
  });

  selectFileBtn.onclick = () => fileInput.click();

  fileInput.onchange = (event) => {
    selectedFile = event.target.files[0];
    if (selectedFile) {
      statusDiv.textContent = `已选择: ${selectedFile.name}`;
      statusDiv.classList.remove('error');
      startImportBtn.disabled = false;
    }
  };

  startImportBtn.onclick = async () => {
    if (!selectedFile) return;
    
    startImportBtn.disabled = true;
    statusDiv.textContent = '处理中...';
    
    const reader = new FileReader();
    reader.onload = async (e) => {
      try {
        await chrome.scripting.executeScript({
          target: { tabId: tab.id },
          function: (data) => {
            window.postMessage({ 
              type: 'IMPORT_GRADES', 
              data: Array.from(data)
            }, '*');
          },
          args: [Array.from(new Uint8Array(e.target.result))]
        });
        window.close();
      } catch (error) {
        console.error(error);
        statusDiv.textContent = '导入失败，请重试';
        statusDiv.classList.add('error');
        startImportBtn.disabled = false;
      }
    };
    reader.readAsArrayBuffer(selectedFile);
  };
});